package com.example.nexttome_mobile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.ProgressBar;
import android.widget.TextView;

public class AsyncGET extends AsyncTask<TextView, Void, String>{

	private TextView myTextView;
	String result = "fail";
	private Context context;
	private String address;
	
	public AsyncGET(Context con, String address){
		this.context = con;
		this.address = address;
	}
	
	@Override
	protected String doInBackground(TextView... params) {
		this.myTextView = params[0];
		return makeHttpRequest();
    }

	private String makeHttpRequest() {
		String url = "https://jbossews-nexttome.rhcloud.com/buscarMobile?serv=1&dir="+address;
		BufferedReader inStream = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpRequest = new HttpGet(url);
			HttpResponse response = httpClient.execute(httpRequest);
			inStream = new BufferedReader(
					new InputStreamReader(
							response.getEntity().getContent()));
			StringBuffer buffer = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ((line = inStream.readLine()) != null) {
				buffer.append(line + NL);
			}
			inStream.close();
			result = buffer.toString();			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inStream != null) {
				try {
					inStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
	
	protected void onPostExecute(String page)
	{   
		myTextView.setText(page);
    	String json = myTextView.getText().toString();
    	try {
			JSONObject obj = new JSONObject(json);
			JSONArray jArray = obj.getJSONArray("data");
			Intent in = new Intent(context, Map.class);
			for(int i=0; i<jArray.length(); i++){
				JSONObject json_data = jArray.getJSONObject(i);
				in.putExtra("latitud"+i, json_data.getString("latitud"));
				in.putExtra("longitud"+i, json_data.getString("longitud"));
			}
			context.startActivity(in);
			MainActivity.ac.finish();
		} catch (JSONException e) {
			e.printStackTrace();
		}
    	
    	
	}
}
